/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.panpf.sketch.sample.util;

import me.panpf.sketch.datasource.DataSource;
import me.panpf.sketch.util.SketchUtils;
import me.panpf.sketch.util.Utils;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;

import java.io.*;

/**
 * SaveImageAsyncTask
 */
public class SaveImageAsyncTask {
    private Context context;
    private DataSource dataSource;
    private String imageUri;
    private TaskDispatcher taskDispatcher;

    public SaveImageAsyncTask(Context context, DataSource dataSource, String imageUri) {
        this.context = context;
        this.dataSource = dataSource;
        this.imageUri = imageUri;

    }


    private Object doBackground() {
        File dir = null;
        boolean mkdirs;
        if (dir == null) {
            dir = context.getFilesDir();
        }
        if (dir == null) {
            return null;
        } else if (!dir.exists()) {
            mkdirs = dir.mkdirs();
            if (mkdirs) {
            }
        }

        File outImageFile = new File(dir, SketchUtils.generatorTempFileName(dataSource, imageUri));
        if(outImageFile.exists()){
            return "This image is the local no need to save";
        }
        try {
            boolean newFile = outImageFile.createNewFile();
            if (newFile) {
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            outputStream = new FileOutputStream(outImageFile);
            inputStream = dataSource.getInputStream();
            byte[] data = new byte[1024];
            int length;
            while ((length = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            SketchUtils.close(outputStream);
            SketchUtils.close(inputStream);
        }
        return outImageFile;
    }

    /**
     * onPostExecute
     * @param outFile
     */
    protected void onPostExecute(Object outFile) {
        if(outFile instanceof String){
            context.getUITaskDispatcher().asyncDispatch(() -> Utils.toast(context, "This image is the local no need to save"));
            return;
        }
        if (outFile instanceof File) {
            File dir = ((File) outFile).getParentFile();
            Utils.toast(context, "已保存到 " + dir.getPath() + "目录");
        } else {
            Utils.toast(context, "保存图片失败，请重试");
        }
    }

    /**
     * execute
     * @param s1
     */
    public void execute(String s1) {
        if (taskDispatcher == null) {
            taskDispatcher = context.createParallelTaskDispatcher("save", TaskPriority.DEFAULT);
        }

        taskDispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                Object out = doBackground();
                context.getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        onPostExecute(out);
                    }
                });
            }
        });
    }
}
